<?php
require 'Config.php';
class redisCache{
	protected $redis;
	//private static $instance;
	public function __construct(){
		try{
		$this->redis = new \Redis();
		$this->redis->connect(CACHE_HOST,CACHE_PORT);
		} catch(Exception $e){
			die($e->getMessage());
		}
	}
	/*public static function getInstance(){
		if(empty(self::$instance)){
			self::$instance = new redisCache();
		}
		return self::$instance;
	}*/
	
	/*
	*Tcp服务链接描述符存为值，伞架id存为键
	*/
	public function setTcpVal($k,$v){                
		$kCheck = $this->redis->keys("Tcp*$k");
		if(!$kCheck){
			$this->redis->set("Tcp".$v.$k,$v);  //将链接描述符和伞架坐标ID组装为redis中string字符类型的key
		}else{
			return 0;
		}
	}

	/*
	*websocket服务链接描述符存为值，用户手机号存为键
	*/
	public function setWebVal($k,$v){
		$kCheck = $this->redis->keys("Web*$k");
		if(!$kCheck){
			$this->redis->set("Web".$v.$k,$v);  //将链接描述符和伞架坐标ID组装为redis中string字符类型的key
		}else{
			return 0;
		}
	}
	
	/*
	*跟具手机号获取Tcp服务链接的链接描述符
	*/
	public function getWebVal($k){                 
		$k = $this->redis->keys("Web*$k");
		if(!empty($k)){
			$v = $this->redis->get($k[0]);
			return $v;
		}else{
			return 0;
		}
	}
	
	/*
	*跟具手机号获取Tcp服务链接的链接描述符
	*/
	public function getTcpVal($k){                 
		$k = $this->redis->keys("Tcp*$k");
		if(!empty($k)){
			$v = $this->redis->get($k[0]);
			return $v;
		}else{
			return 0;
		}
	}

	/*
	*根据Websocket链接描述符删除对应的值
	*/
	public function delWebVal($v){
		$k = $this->redis->keys("Web$v*");
		if(!empty($k)){
			$re = $this->redis->del($k[0]);
			if($re){
				return 1;
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}

	/*
	*根据TCP链接描述符删除对应的值
	*/
	public function delTcpVal($v){
		$k = $this->redis->keys("Tcp$v*");
		if(!empty($k)){
			$re = $this->redis->del($k[0]);
			if($re){
				return 1;
			}else{
				return 0;
			}
		}else{
			return 0;
		}
	}

	/*
	*获取所有的websocket链接描述符
	*/
	public function getWebAll(){
		$re = $this->redis->gets("Web*");
		return $re;
	}

	/*
	*获取所有的TCP链接描述符
	*/
	public function getTcpAll(){
		$re = $this->redis->gets("Tcp*");
		return $re;
	}

	/*
	*清空整个缓存
	*/
	public function delall(){
		$tcp = $this->redis->keys("Tcp*");
		$web = $this->redsi->keys("Web*");
		foreach($tcp as $v){
			$this->redis->del($v);
		}
		foreach($web as $v){
			$this->redis->del($v);
		}
	}

}

